package nuc.SQLoperation;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SQLiteOperationHelper extends SQLiteOpenHelper {
	/*
	 * 创建事务 保证数据库执行失败执行回滚 
	 * db.beginTransaction(); 
	 * db.setTransactionSuccessful();
	 * db.endTransaction();
	 */
	SQLiteDatabase db = getReadableDatabase();

	public SQLiteOperationHelper(Context context, String name,
			CursorFactory factory, int version) {
		super(context, Constant.DB_NAME, factory, version);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL("CREATE TABLE IF NOT EXISTS " + Constant.tableName + " ("
				+ Constant.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ Constant.title + " text," + Constant.content + " text,"
				+ Constant.photoURL + " text," + Constant.lastdate + " text)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

	public boolean insert(ContentValues values) {
		db.insert(Constant.tableName, null, values);
		return true;
	}

	public Cursor query(String limit) {
		Cursor c = db.query(Constant.tableName, null, null, null, null, null,
				limit);
		return c;
	}
	public Cursor queryByid(String id) {
		Cursor c = db.query(Constant.tableName, null, "_id="+id, null, null, null,null);
		return c;
	}
	
	public boolean update(Long id,ContentValues values){
		String whereClause = "_id=?";
		String[] whereArgs = { String.valueOf(id) };
		try {
			db.beginTransaction();
			db.update(Constant.tableName, values, whereClause, whereArgs);
			db.setTransactionSuccessful();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		finally{
			db.endTransaction();
		}
		
		return true;
	}

	public void del(long id) {
		String whereClause = "_id=?";
		String[] whereArgs = { String.valueOf(id) };
		if (db != null) {
			db.beginTransaction();
			db.delete(Constant.tableName, whereClause, whereArgs);
			db.setTransactionSuccessful();
			db.endTransaction();
		}
	}
	public boolean reset(){
		try{
			db.beginTransaction();
			db.execSQL("drop table SimpleNote");
			db.execSQL("CREATE TABLE IF NOT EXISTS " + Constant.tableName + " ("
					+ Constant.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
					+ Constant.title + " text," + Constant.content + " text,"
					+ Constant.photoURL + " text," + Constant.lastdate + " text)");
			db.setTransactionSuccessful();
		}
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		finally{
			db.endTransaction();
		}
		return true;
	}

}
